package com.atguigu.day10;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class Flink06_UDFS_UDAF {
    public static void main(String[] args) {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        env.setParallelism(1);

        //3.从端口读取数据并转为JavaBean
        SingleOutputStreamOperator<WaterSensor> streamOperator = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //4.将流转为表
        Table table = tableEnv.fromDataStream(streamOperator);

        //不注册直接使用
   /*     table
                .groupBy($("id"))
                .select($("id"),call(MyUDAF.class, $("vc")).as("vcAvg"))
                .execute()
                .print();*/
        //先注册再使用
        tableEnv.createTemporarySystemFunction("MyAvg", MyUDAF.class);

            /*table
                .groupBy($("id"))
                .select($("id"),call("MyAvg", $("vc")).as("vcAvg"))
                .execute()
                .print();*/

        tableEnv.executeSql("select id,MyAvg(vc) from "+table+" group by id").print();

    }

    public static class MyAcc{
        public Integer vcSum;
        public Integer vcCount;
    }

    //自定义聚合函数 多进一出 求vc平均值
    public static class MyUDAF extends AggregateFunction<Double,MyAcc>{
        @Override
        public MyAcc createAccumulator() {
            MyAcc acc = new MyAcc();
            acc.vcCount = 0;
            acc.vcSum = 0;
            return acc;
        }

        public void accumulate(MyAcc acc,Integer value){
            acc.vcSum += value;
            acc.vcCount++;
        }

        @Override
        public Double getValue(MyAcc accumulator) {
            return accumulator.vcSum*1D/accumulator.vcCount;
        }


    }

}
